package com.csscaps.auth.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csscaps.auth.dao.SysOrgDao;
import com.csscaps.auth.dao.SysUserDao;
import com.csscaps.auth.dao.SysUserRoleDao;
import com.csscaps.auth.model.Mail;
import com.csscaps.auth.model.SysOrg;
import com.csscaps.auth.model.SysUser;
import com.csscaps.auth.model.SysUserRole;
import com.csscaps.system.base.BaseTreeNode;
import com.csscaps.system.shiro.ShiroUser;
import com.csscaps.system.utils.Constants;
import com.csscaps.system.utils.DateUtils;
import com.csscaps.system.utils.MailUtil;
import com.csscaps.system.utils.UUIDGenerator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class SysUserService extends SysUserDao {

	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysOrgDao sysOrgDao;
	
	/**
	 * 删除用户
	 * 
	 * @param userIdArr
	 * @return
	 */
	@Transactional
	public boolean deleteUser(String[] userIdArr) {
		if (userIdArr.length == 0)
			return false;
		try {
			for (int i = 0; i < userIdArr.length; i++) {
				// step 1：删除用户信息
				sysUserDao.deleteByPk(userIdArr[i]);
				// step 2:删除用户上关联的角色信息
				SysUserRole sysUserRole = new SysUserRole();
				sysUserRole.setUserroleUserUuid(userIdArr[i]);
				sysUserRoleDao.deleteByVo(sysUserRole);
			}
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * 用户角色授权 ，支持多对多关系
	 * 
	 * @param userIdArr
	 * @return
	 */
	@Transactional
	public void authorize(String parameter) throws Exception {

		JSONObject parameterObject = JSONObject.fromObject(parameter);
		JSONArray checkUserArr = JSONArray.fromObject(parameterObject
				.get("checkUserList"));
		JSONArray checkedRoleIdsArr = JSONArray.fromObject(parameterObject
				.get("checkedRoleIds"));
		for (int i = 0; i < checkUserArr.size(); i++) {
			JSONObject obj = (JSONObject) checkUserArr.get(i);
			String userId = obj.getString("userUuid");
			String userAccount = obj.getString("userAccount");
			SysUserRole userRole = new SysUserRole();
			userRole.setUserroleUserUuid(userId);
			// step 1 ：先删除用户上全部的的角色信息
			sysUserRoleDao.deleteByVo(userRole);
			// step 2 ：重新建立用户角色关系[ps:一个用户可以对应多个角色，故而用双层循环]
			for (Object roleId : checkedRoleIdsArr) {
				if (!exists(userId, String.valueOf(roleId))) {
					SysUserRole sysUserRole = new SysUserRole();
					sysUserRole.setUserroleRoleUuid(String.valueOf(roleId));
					sysUserRole.setUserroleUuid(UUIDGenerator.genUuidStr());
					sysUserRole.setUserroleUserUuid(userId);
					sysUserRole.setUserroleUserAccount(userAccount);
					sysUserRole.setUserroleCreateTime(new Date());
					sysUserRoleDao.insertByVo(sysUserRole);
				}
			}
		}

	}

	/**
	 * 检测用户是否和该角色存在关联关系
	 * 
	 * @param userId
	 * @param roleId
	 * @return
	 */
	private boolean exists(String userId, String roleId) {
		SysUserRole userRole = new SysUserRole();
		userRole.setUserroleRoleUuid(roleId);
		userRole.setUserroleUserUuid(userId);
		List<SysUserRole> resolut = sysUserRoleDao.selectByVo(userRole);
		return resolut.size() != 0;
	}

	public List<BaseTreeNode> getUserOrgTree(String userId) throws Exception {
		List<BaseTreeNode> basetree = new ArrayList<BaseTreeNode>();
		SysUser user = new SysUser();
		if (userId != null) {
			user = sysUserDao.selectByPK(userId);
		}
		List<SysOrg> orglist = sysOrgDao.selectAll();
		for (SysOrg orglists : orglist) {
			// 排序线路上的机构信息
			BaseTreeNode besat = new BaseTreeNode();
			besat.setId(orglists.getOrgUuid());
			besat.setName(orglists.getOrgName());
			besat.setpId(orglists.getOrgParentUuid());
			besat.setCode(orglists.getOrganizationCode());
			if ((user.getUserOrgUuid() != null)
					&& (user.getUserOrgUuid().equals(orglists.getOrgUuid()))) {
				besat.setChecked(true);
			}
			basetree.add(besat);
		}
		return basetree;
	}
/*	@Transactional
	public void userApprove(Map<String, Object> paraMap) throws Exception {
		
		String userUuid = String.valueOf(paraMap.get("userUuid"));
		String userAccount = String.valueOf(paraMap.get("userAccount"));
		String userEmail = String.valueOf(paraMap.get("email"));
		String approverComment = String.valueOf(paraMap.get("approverComment"));
		String authCodeExpireDateStr = paraMap.get("authCodeExpireDate").toString();
		Subject subject = SecurityUtils.getSubject();
		String loginUserAccount = String.valueOf(((ShiroUser)subject.getPrincipal()).getUserAccount());
		
		SysUser user = new SysUser();
		user.setUserUuid(userUuid);
		user.setApproveStatus(Constants.APPROVE_PASS);
		user.setApproverAccount(loginUserAccount);
		user.setApproverTime(DateUtils.getCurrTime());
		user.setApproverComment(approverComment);
		user.setExpireDate(DateUtils.StrToDate(Constants.DATEFORMAT_Y_M_D, authCodeExpireDateStr));
		sysUserDao.updateByVO(user);
		
		String encryptAuthCode = "";
		
		String authCode = String.valueOf(RandomUtils.getRandomInt(10000));
		String encryptAuthCode = MD5Encrypter.md5Encrypt(authCode, userAccount);
		String authCodeExpireDateStr = paraMap.get("authCodeExpireDate").toString();
		AuthCodeInfo authCodeInfo = new AuthCodeInfo();
		authCodeInfo.setUserUuid(userUuid);
		authCodeInfo.setAuthCode(encryptAuthCode);
		authCodeInfo.setExpireDate(DateUtils.StrToDate(Constants.DATEFORMAT_Y_M_D, authCodeExpireDateStr));
		authCodeInfo.setDeleteStatus(Constants.NOT_DELETED);
		authCodeDao.insertSelective(authCodeInfo);
		
		Mail mail = new Mail();
		mail.setHost(PropertiesUtil.getProperty("mail.host"));
        mail.setReceiver(userEmail);
		mail.setSender(PropertiesUtil.getProperty("mail.sender"));
		mail.setName(PropertiesUtil.getProperty("mail.nickName"));
		mail.setUsername(PropertiesUtil.getProperty("mail.userName"));
		mail.setPassword(AESEncrypter.aesDecrypt(PropertiesUtil.getProperty("mail.password"), Constants.AES_KEY));
		mail.setSubject("授权码");
		mail.setMessage("授权码：" + encryptAuthCode);
		Boolean result = MailUtil.send(mail);
		System.out.println(result);
	}
 
	*/
}
